//
//  BaseEngine.m
//  TSOL
//
//  Created by Yang on 13-7-8.
//  Copyright (c) 2013年 tsol. All rights reserved.
//

#import "BaseEngine.h"
#import "AppConfig.h"


NSString * const kProtocolHelperLocalizedDescription = @"网络连接错误";

@implementation BaseEngine


+ (BaseEngine *)sharedEngine
{
    static dispatch_once_t pred;
    
    static BaseEngine *sharedSingleton;
    
    dispatch_once(&pred,^{sharedSingleton=[[self alloc] initSingleton];} );
    
    return sharedSingleton;
}


- (id)initSingleton
{
    if(self=[super init]){
        
        self = [[BaseEngine alloc] initWithHostName:kServerDomain customHeaderFields:nil];
        self.httpMethod = @"POST";
        self.useCached = NO;
        self.postDict = [[NSMutableDictionary alloc] init];
        self.postFileDict = [[NSMutableDictionary alloc] init];
        
        self.nonAuthorPath = @[];
    }
    return self;
}




- (MKNetworkOperation*)RunRequest:(NSMutableDictionary *)  dict
                             path:(NSString *)      path
                completionHandler:(ResponseBlock)   completionBlock
                     errorHandler:(MKNKErrorBlock)  errorBlock
                    finishHandler:(FinishBlock)     finishBlock
{
    if (dict==nil) {
        dict = [[NSMutableDictionary alloc] init];
    }
    
    NSDictionary *agent = [AppConfig getAgent];
    id agent_pwd = [agent objectForKey:KFC_AGENT_PWD];
    id agent_mobile = [agent objectForKey:KFC_AGENT_MOBILE];
    id agent_ucid = [agent objectForKey:KFC_AGENT_UCID];
    agent_pwd = agent_pwd == nil ? @"" : agent_pwd;
    agent_mobile = agent_mobile == nil ? @"" : agent_mobile;
    agent_ucid = agent_ucid == nil ? @"" : agent_ucid;
    [dict setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"version"];
    [dict setObject:mydeviceUniqueIdentifier() forKey:@"uuid"];
    [dict setObject:@"1" forKey:@"deviceType"];
    [dict setObject:@"apple" forKey:@"channel"];
    [dict setObject:[AppConfig getAPPUserToken] forKey:@"token"]; ///FIXED
    [dict setObject:agent_pwd forKey:@"KFC_AGENT_PWD"]; ///后面加
    [dict setObject:agent_mobile forKey:@"KFC_AGENT_MOBILE"]; ///后面加
    [dict setObject:agent_ucid forKey:@"KFC_AGENT_UCID"]; ///后面加
    if (!self.useCached) {
        NSDate *date = [NSDate date];
        NSTimeInterval timeInterval = [date timeIntervalSince1970]*1000;///set s to ms
        [dict setObject:[NSString stringWithFormat:@"%.0f", timeInterval] forKey:@"timer"];
    }
    
   
    
    //loading加载
    showLoadingView();
    
    MKNetworkOperation *op = [self operationWithPath:path
                                              params:dict
                                          httpMethod:self.httpMethod];
    
    ///file upload
    if (self.postFileDict && [self.postFileDict count]>0) {
        
        for (NSString *key in [self.postFileDict allKeys])
        {
            [op addFile:[self.postFileDict valueForKeyPath:key] forKey:key];
        }
    }
    
    
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        DLog(@"MKNET URL=%@%@",completedOperation.url, dict);
        
        NSString *response = [completedOperation responseString];
        
        id reDict = [response objectFromJSONString];
        DLog(@"MKNET RESPONSE=%@",reDict);
        if (reDict) {
            int errCode = [[reDict valueForKey:@"code"] intValue];
            
            if (errCode==1){
                completionBlock(reDict);
                reDict = nil;
            } else if (errCode == -1) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TokenFailed" object:nil userInfo:nil onMainThread:YES];
            } else {
                NSString *msg = [reDict objectForKey: @"msg"];
                if (msg != nil && msg.length > 0) {
                    showAlertMessage(msg);
                } else {
                    showCustomAlertMessage(@"网络错误");
                }
                
            }
            
        }
        else{
            reDict = @{@"code":@"400",@"msg":@"服务器请求错误"};
        }
        
        finishBlock(reDict);
        //loading卸载
        hideLoadingView();
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        showIndicator(NO, nil);
        error = [[NSError alloc] initWithDomain:kProtocolHelperLocalizedDescription code:201 userInfo:nil];
        errorBlock(error);
        //loading卸载
        hideLoadingView();
    }];
    
    [self enqueueOperation:op];
    ///完成上传后把请求体清空
    [self.postDict removeAllObjects];
    [self.postFileDict removeAllObjects];
    self.useCached = YES;

    return op;
}



- (void)cancelOperation:(MKNetworkOperation *)op
{
    showIndicator(NO, nil);
    if (op && [op isExecuting]) {
        [op cancel];
    }
}
@end
